package com.zhongke.cotrun.common.util;

import com.zhongke.cotrun.mapper.*;
import com.zhongke.cotrun.model.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Component
public class IntegralUtil {

    @Autowired
    IntegralMapper integralMapper;//积分类型
    @Autowired
    IntegralRecordMapper integralRecordMapper;//积分规则

    @Autowired
    UserIntegralHistoryMapper userIntegralHistoryMapper;//积分历史
    @Autowired
    UserAllIntegralMapper userAllIntegralMapper;//积分账户

    @Autowired
    MembershipValuesMapper membershipValuesMapper;//积分所属值


    //积分工具类

    /**
     * 增加积分和消费积分
     * 使用积分规则
     *
     * @param port       积分触发接口
     * @param membership //会员等级
     * @param userType   用户角色
     * @param userId     用户id
     * @param session
     * @return
     * @throws ParseException
     */
    @Transactional
    public Boolean addIntegral(String port, String membership, List<String> userType, Integer userId, String historyExplain, HttpSession session) throws ParseException {
//        Collections.max(list)
        //1根据积分接口找到积分值
        Integral integral = integralMapper.selectIntegralByPort(port);//积分类型
        if (integral == null) {
            return false;
        }
        Integer integralId = integral.getIntegralId();//获取类型的id
        //2.根据积分类型id获取积分规则
        IntegralRecord integralRecord = integralRecordMapper.selectIntegralRecordByIntegralNameId(integralId);
        //3.没有获取就是空返回false
        if (integralRecord == null) {
            return false;
        }

        Integer integralRecordId = integralRecord.getIntegralRecordId();//获取规则的id
        Integer isPerpetual = integralRecord.getPerpetual();//获取是否永久0 否 1是
        Date startTime = integralRecord.getStartTime();//开始时间
        Date finiTime = integralRecord.getFinishTime();//结束时间

        //4.对比是否在时间之内
        if (1 != isPerpetual) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            String nowString = df.format(new Date());//获取当前的时间
            Date now = df.parse(nowString);//现在 的时间
            if (now.before(startTime) || now.after(finiTime)) {
                return false;
            }
        }
        //5.获取规则里面的值根据规则id，会员等级，用户等级


        List<BigDecimal> v = new ArrayList<>();
        MembershipValues membershipValue1 = membershipValuesMapper.selectOfMembershipValue(integralRecordId, "全部", "全部");

        if (membershipValue1 != null) {
            v.add(membershipValue1.getIntegralValue());
        }
        MembershipValues membershipValue2 = membershipValuesMapper.selectOfMembershipValue(integralRecordId, membership, "全部");
        if (membershipValue2 != null) {
            v.add(membershipValue2.getIntegralValue());
        }


        for (String u : userType) {

            MembershipValues membershipValue3 = membershipValuesMapper.selectOfMembershipValue(integralRecordId, "全部", u);
            if (membershipValue3 != null) {
                v.add(membershipValue3.getIntegralValue());
            }
            MembershipValues membershipValues = membershipValuesMapper.selectOfMembershipValue(integralRecordId, membership, u);
            if (membershipValues != null) {
                v.add(membershipValues.getIntegralValue());
            }


        }

        System.out.println(v);
        //多个身份取最大的值
        BigDecimal value = Collections.max(v);
        Integer a = 0;
//6.判断值是否小于0


        if (value != null) {
            a = value.compareTo(new BigDecimal(0));
            if (a >= 0) {

                UserAllIntegral userAllIntegral0 = new UserAllIntegral();
                userAllIntegral0.setAllValue(value);//设置值
                userAllIntegral0.setUserId(userId);
                if (userAllIntegralMapper.insertUserAlllntegralMapper(userAllIntegral0)) {
                    //新建历史   1积分类型的id  2积分规则的id   3积分值  4积分说明 5 用户id
                    //6.所属一级 7所属二级
                    //积分规则

                    insertHistory(userId, integralId, value, integralRecord.getIntegralRecordId(), integral.getIntegralName(), integralRecord.getRankOne(), integralRecord.getRankTwo(), session);
                    return true;
                }

            } else {
                //消费积分
                reduceTheIntegral(userId, value, integralId, integralRecordId, integral.getIntegralName(), integralRecord.getRankOne(), integralRecord.getRankTwo(), session);
                return true;
            }

        }

        return false;

    }


    /**
     * 消费积分的方法
     *
     * @param userId  //用户id
     * @param value   //用户的值
     * @param session
     * @return
     */

    public Boolean reduceTheIntegral(Integer userId, BigDecimal value, Integer interalNameId, Integer integralRecordId, String historyExplain, Integer rankOneOf, Integer rankTwoOf, HttpSession session) {
        //1.获取用户的积分账户

        List<UserAllIntegral> a = userAllIntegralMapper.selectUserAllIntegral(userId);//用户的账户

        for (UserAllIntegral ual : a) {
            BigDecimal m = ual.getAllValue();//当前的值
            BigDecimal b = m.add(value);//减去后的值
            int c = b.compareTo(new BigDecimal(0));

            if (c == 0) {
                //等于0就删除
                if (userAllIntegralMapper.delectThisUserAllIntegral(ual.getAllIntegralId())) {
                    insertHistory(userId, interalNameId, value, integralRecordId, historyExplain + value, rankOneOf, rankTwoOf, session);
                    //插入历史没写
                    return true;
                }
                return false;
            }

            if (c > 0) {
                if (userAllIntegralMapper.updateUserAllIntegral(b, ual.getUserId())) {
                    insertHistory(userId, interalNameId, value, integralRecordId, historyExplain + value, rankOneOf, rankTwoOf, session);
                    return true;
                }

                return false;
            }
            if (c < 0) {
                userAllIntegralMapper.delectThisUserAllIntegral(ual.getAllIntegralId());
                value = b;
                insertHistory(userId, interalNameId, m.negate(), integralRecordId, historyExplain + value, rankOneOf, rankTwoOf, session);
                continue;

            }

        }
        return false;

    }

    /**
     * 新建历史记录
     *
     * @param userId        用户id
     * @param interalNameId 积分类型
     * @param value         插入的值
     * @param session
     */
    private void insertHistory(Integer userId, Integer interalNameId, BigDecimal value, Integer integralRecordId, String historyExplain, Integer rankOneOf, Integer rankTwoOf, HttpSession session) {
        UserIntegralHistory userIntegralHistory = new UserIntegralHistory();
        userIntegralHistory.setIntergralNameId(interalNameId);//积分类型
        userIntegralHistory.setUserId(userId);//用户
        int c = value.compareTo(new BigDecimal(0));
        if(c>0){
            userIntegralHistory.setIntegralValue("+"+value);//值
        }else {
            userIntegralHistory.setIntegralValue(""+value);//值
        }

        userIntegralHistory.setRankOneOf(rankOneOf);//所属一级
        userIntegralHistory.setRankTwoOf(rankTwoOf);//所属二级
        userIntegralHistory.setIntegralRecordId(integralRecordId);//积分规则id
        userIntegralHistory.setHistoryExplain(historyExplain);//积分接口说明
        userIntegralHistoryMapper.insertUserIntegralHistory(userIntegralHistory);
        session.setAttribute("value", value);
    }




}
